const redis = require('redis');

module.exports = class RedisClient {
    constructor(cfg) {

        var client = redis.createClient(cfg.redis);
        client.select(cfg.redis.database);

        client.on("error", function(err) {
            console.log("Error :", err);
        });

        client.on('connect', function() {
            console.log('Redis连接成功：' + cfg.redis.host + ':' + cfg.redis.port);
        });

        this.client = client;
    }

    /** 
     * 添加string类型的数据 
     * @param key 键 
     * @params value 值  
     * @params expire (过期时间,单位秒;可为空，为空表示不过期) 
     * @param cb(err,result) 
     */
    set(key, value, expire, cb) {
        let that = this;
        that.client.set(key, value, function(err, result) {

            if (err) {
                console.log(err);
                if (cb) cb(err, null);
                return;
            }

            if (!isNaN(expire) && expire > 0) {
                that.client.expire(key, parseInt(expire));
            }

            if (cb) cb(null, result);
        })
    }

    async get(key) {
        let that = this;
        let doc = await new Promise((resolve) => {
            that.client.get(key, function(err, res) {
                return resolve(res);
            });
        });
        return doc;
    }

    async incr(key) {
        let that = this;
        let doc = await new Promise((resolve) => {
            that.client.incr(key, function(err, res) {
                return resolve(res);
            });
        });
        return doc;
    }

    async decr(key) {
        let that = this;
        let doc = await new Promise((resolve) => {
            that.client.decr(key, function(err, res) {
                return resolve(res);
            });
        });
        return doc;
    }
}